package com.sunday.gateway.security.permissions;

import com.sunday.boot3.user.center.pojo.dto.permissions.ListPermissionsResDTO;
import com.sunday.boot3.user.center.pojo.dto.user.GetAuthUserReqDTO;
import com.sunday.boot3.user.center.provider.PermissionsProvider;
import com.sunday.boot3.user.center.provider.UserProvider;
import com.sunday.common.core.enums.ErrorCodeEnum;
import com.sunday.common.core.exception.BusinessException;
import com.sunday.common.core.permissions.PermissionsDecode;
import com.sunday.common.core.remoting.base.response.Response;
import com.sunday.common.core.remoting.rpc.response.RPCResponseHandler;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Optional;

/**
 * 权限管理器
 *
 * @author sunday
 * @since 2024/9/26
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class PermissionsManager implements InitializingBean {

    @DubboReference
    private PermissionsProvider permissionsProvider;

    @Getter
    private PermissionsDecode decode;

    private static PermissionsManager permissionsManager = null;

    public static PermissionsManager getInstances() {
        return permissionsManager;
    }

    @Override
    public void afterPropertiesSet() {
//        Collection<ListPermissionsResDTO> permissionsList = getPermissions();
//        permissionsList.stream().forEach(permissions -> log.info("========== {}", permissions));
        decode = PermissionsDecode.of(getPermissions(), ListPermissionsResDTO::getUrl, ListPermissionsResDTO::getPosition, ListPermissionsResDTO::getCode);
        permissionsManager = this;
    }

    protected Collection<ListPermissionsResDTO> getPermissions() {
        return Optional.ofNullable(RPCResponseHandler.invoke(() -> permissionsProvider.list()))
                .filter(Response::isSuccess)
                .map(Response::getBody)
                .filter(ObjectUtils::isNotEmpty)
                .orElseThrow(() -> new BusinessException(ErrorCodeEnum.B0_300));
    }


}
